package com.cheney.common.sentinel.handle;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author si.chen
 * @date 2021/6/18 14:20
 */
@Slf4j
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {

        Map<String, Object> info = new HashMap<>(2);
        if (e instanceof FlowException) {
            info.put("code", 100);
            info.put("msg", "接口限流了");
        } else if (e instanceof DegradeException) {
            info.put("code", 101);
            info.put("msg", "服务降级了");
        } else if (e instanceof ParamFlowException) {
            info.put("code", 102);
            info.put("msg", "热点参数限流了");
        } else if (e instanceof SystemBlockException) {
            info.put("code", 103);
            info.put("msg", "触发系统保护规则");
        } else if (e instanceof AuthorityException) {
            info.put("code", 104);
            info.put("msg", "授权规则不通过");
        }
        //设置json返回
        httpServletResponse.setStatus(500);
        httpServletResponse.setHeader("content-type", "application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(info));
    }
}
